package com.dc.helloworld.controller;

import com.dc.helloworld.dao.DepartmentDao;
import com.dc.helloworld.dao.EmployeeDao;
import com.dc.helloworld.po.Department;
import com.dc.helloworld.po.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;


import java.util.Collection;

@Controller
public class EmployeeController {

    @Autowired
    EmployeeDao employeeDao;
    @Autowired
    DepartmentDao departmentDao;

    @RequestMapping("/emps")
    public String list(Model model){
        Collection<Employee> employees = employeeDao.getAllEmployees();
        model.addAttribute("emps",employees);
        return "emp/list";
    }


    //去添加页
    @GetMapping("/emp")
    public String toAdd(Model model){
        //查出所有部门信息
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("departments",departments);
        return "emp/add";
    }


    //添加员工 或 修改员工
    @PostMapping("/emp")
    public String add(Employee employee){
        System.out.println("Debug===>"+employee);
        employeeDao.save(employee);
        return "redirect:/emps";
    }


    //去修改页
    @GetMapping("/emp/{id}")
    public String toUpdate(@PathVariable("id")Integer id, Model model){
        //查出所有部门信息
        Employee employee = employeeDao.getEmployeeByID(id);
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("emp",employee);
        model.addAttribute("departments",departments);
        return "emp/update";
    }



    //删除员工
    @DeleteMapping("/emp/{id}")
    public String delEmp(@PathVariable("id")Integer Id){
        employeeDao.delete(Id);
        return "redirect:/emps";
    }


}
